//
//  Custody.m
//  TourDeGarde
//
//  Created by Guillaume SOURDRILLE on 03/05/12.
//  Copyright (c) 2012 Astek. All rights reserved.
//

#import "Custody.h"

@implementation Custody
@synthesize beginDate,endDate,name,active,uniqueId;

- (id)initCustody
{
    self = [super init];
    if (self) {
        uniqueId = [self uuid];
        active = YES;
    }
    return self;
}


-(void)encodeWithCoder:(NSCoder *)aCoder{
	
	[aCoder encodeObject:beginDate forKey:@"beginDate"];
	[aCoder encodeObject:endDate forKey:@"endDate"];
	[aCoder encodeObject:name forKey:@"name"];
    [aCoder encodeObject:uniqueId forKey:@"uniqueId"];
    [aCoder encodeBool:active forKey:@"active"];
}

-(id)initWithCoder:(NSCoder *)aDecoder {
	self= [super init];
	beginDate=[aDecoder decodeObjectForKey:@"beginDate"];
	endDate=[aDecoder decodeObjectForKey:@"endDate"];
	name=[aDecoder decodeObjectForKey:@"name"] ;
    uniqueId=[aDecoder decodeObjectForKey:@"uniqueId"] ;
    active=[aDecoder decodeBoolForKey:@"active"] ;
	
	return self;
}

- (NSString *)uuid
{
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *result =  (__bridge NSString *)uuidStringRef ;
    return result;
}

- (NSString *)validate{
    
    NSString *result  = [[NSString alloc]init];
    NSMutableArray *errors = [[NSMutableArray alloc]init];
    
    if (name == nil || [name isEqualToString:@""]){
        [errors addObject:NSLocalizedString(@"Custody.error.name", @"")];
    }
    
    if (beginDate == nil){
        [errors addObject:NSLocalizedString(@"Custody.error.beginDate", @"")];
    }
    
    if (endDate == nil){
        [errors addObject:NSLocalizedString(@"Custody.error.endDate", @"")];
    }
    
    if ([endDate timeIntervalSinceDate:beginDate] < 0){
        [errors addObject:NSLocalizedString(@"Custody.error.date", @"")];
    }
    
    if (errors.count > 0){
      result = [errors componentsJoinedByString:@"\n"];
    }
        
        return result;
}

- (NSInteger)timeBetween{
    NSTimeInterval distanceBetweenDates = [endDate timeIntervalSinceDate:beginDate];
    double secondsInAnHour = 3600;
    NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
    return hoursBetweenDates;
    
}

@end
